package com.zztl.infiniteBand.ui.fragment


import android.os.Handler
import android.view.View
import com.clj.fastble.BleManager

import com.clj.fastble.callback.BleDataCountCallback.BleStepCallback
import com.clj.fastble.callback.BleDataCountCallback.BleUserInfoCallback
import com.clj.fastble.utils.BleLog

import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpFragment
import com.zztl.infiniteBand.eventbus.ConnectedEvent
import com.zztl.infiniteBand.eventbus.SyncStepCount
import com.zztl.infiniteBand.eventbus.WatchStepEvent
import com.zztl.infiniteBand.model.TargetStepBean
import com.zztl.infiniteBand.net.requestBean.SyncStepRequest
import com.zztl.infiniteBand.presenter.SportPresenter
import com.zztl.infiniteBand.ui.view.mvpview.TargetStepView
import com.zztl.infiniteBand.util.DateUtils
import com.zztl.infiniteBand.util.TextCheckUtil
import kotlinx.android.synthetic.main.activity_measure_bloodpressure.*
import kotlinx.android.synthetic.main.fragment_sport_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit


/**
 * @desc
 * @auth ${user}
 * @time 2018/9/13  16:05
 */
class SportFragment : BaseMvpFragment<TargetStepView, SportPresenter>(), TargetStepView {

    /*  @BindView(R.id.dialview)
      lateinit var dialview: DialView*/

    val TAG = "SportFragment"

    lateinit var mSportPresenter: SportPresenter
    private val mHandler by lazy {
        Handler()
    }
    lateinit var threadPool: ScheduledExecutorService
    lateinit var scheduledFuture: ScheduledFuture<*>

    private var goalStep = 10000
    private var isFirstSync = true
    private var isActivityCreated = false
    private var syncedWatchStep = 0;


    override fun createPresenter(): SportPresenter {
        mSportPresenter = SportPresenter()
        return mSportPresenter
    }

    override fun setLayoutId(): Int = R.layout.fragment_sport_layout


    override fun initData() {
        isActivityCreated = true;
        EventBus.getDefault().register(this)

        threadPool = Executors.newScheduledThreadPool(1).apply {
            scheduledFuture = scheduleWithFixedDelay(EchoServer(), 0, 1, TimeUnit.SECONDS)
        }
        getBandData()
    }


    /**
     * 计算距离22:30:00的剩余时间，刷新倒计时时间
     */
    internal inner class EchoServer : Runnable {
        override fun run() {
            activity!!.runOnUiThread {
                btnMeasure?.let { btnMeasure ->
                    DateUtils.isInReceiveTime.let {
                        if (it) {
                            btnMeasure.visibility = View.VISIBLE

                        } else {
                            btnMeasure.visibility = View.GONE
                        }
                    }
                }
            }
        }

    }

    override fun onResume() {
        BleLog.i("SportFragment--------------->onResume")
        super.onResume()
    }


    override fun onHiddenChanged(hidden: Boolean) {
        BleLog.i("SportFragment--------------->onHiddenChanged--" + hidden)
        if (!hidden && isActivityCreated) {
            getBandData()
        }
    }

    private fun getBandData() {
        if (BleManager.getInstance().isConnected) {
            BleManager.getInstance().dataComonent.getActivityCount { snNumber ->
                BleManager.getInstance().dataComonent.getStep(snNumber, 0, object : BleStepCallback {
                    override fun getOneceStep(step: Int) {
                    }

                    override fun getStep(step: Int) {
                        setUiByStep(step)
                        syncedWatchStep = step
                        presenter?.syncStep(SyncStepRequest(BleManager.getInstance().connecredDevice.mac, step), activity!!)
                    }
                })
            }
            mHandler.postDelayed({
                BleManager.getInstance().dataComonent.getHeartRate { heartRate ->
                    if (heartRate == "0") {
                        tv_heart.text = "--"
                    } else {
                        tv_heart.text = heartRate
                    }
                }
            }, 1500)


        }

    }


    override fun getTargetStep(bean: TargetStepBean) {
        bean.data?.rows?.apply {
            this.forEach { rowsBean ->
                if (rowsBean.type == "0") {
                    goalStep = rowsBean.stepNumber.toInt()

                }
            }
        }

    }

    override fun getTargetStepFail() {

    }

    /**
     * 同步步数的回调
     */
    override fun syncStepSuccess(b: Boolean, mileageSum: Int) {
        if (b) {
            isFirstSync = false
            tv_target_step.text = getString(R.string.同步步数) + mileageSum
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(stepEvent: WatchStepEvent) {
        setUiByStep(stepEvent.step)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Evnent(event: ConnectedEvent) {
        if (!event.isConnected) {
            resetUi()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Evnent(event: SyncStepCount) {
        tv_target_step.text = getString(R.string.同步步数) + event.syncedStep
    }

    private fun resetUi() {
        setUiByStep(0)
        tv_distance.text = 0.toString()
        tv_cal.text = 0.toString()
        tv_heart.text = 0.toString()

    }


    private fun setUiByStep(step: Int) {
        currentStep.text = step.toString()
        dialview.setProgress(Math.min(step.toFloat() / goalStep, 1f))

        getDistance(step).apply {
            tv_distance.text = TextCheckUtil.formatDouble2(this).toString()
        }
        getCal(step).apply {
            tv_cal.text = TextCheckUtil.formatDouble2(this).toString()
        }
    }


    private fun getCal(step: Int): Double {

        return BleManager.WEIGHT * 0.0006564 * step

    }

    private fun getDistance(step: Int): Double {
       return step.toDouble() * BleManager.HEIGHT * 0.45 / 100.0 / 1000.0
    }


    override fun onDetach() {
        threadPool.shutdownNow()
        scheduledFuture.cancel(true)
        mHandler.removeCallbacksAndMessages(null)
        super.onDetach()
    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }


}
